/**
 * @ClassName: ApiVersionInterceptor
 * @Description: java类作用描述
 * @Author: zdl
 * @Date: 2022/3/16 15:16
 */
package com.example.a_lib.http.api;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.a_lib.BizApplication;
import com.example.a_lib.config.ServerFlavorConfig;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ClassName: ApiVersionInterceptor
 * @Description: java类作用描述
 * @Author: zdl
 * @Date: 2022/3/16 15:16
 */
public class ApiVersionInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        //设置业务逻辑所需的header
        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        headerParams.put("nonce", UUID.randomUUID().toString().replace("-", ""));
        Map<String, String> stringStringMap = BizApplication.Companion.get().initHeads();
//        headerParams.put("token", LoginUserUtils.getInstance().getLoginUser().getToken() + "");
//        headerParams.put("userid", LoginUserUtils.getInstance().getLoginUser().getUid() + "");
//        headerParams.put("userphone", LoginUserUtils.getInstance().getLoginUser().getMobile() + "");
        headerParams.putAll(stringStringMap);


//        headerParams.put("appversion", "android." + AppUtils.getAppVersionName().split("_")[0]);
//        headerParams.put("sign", calcSign(headerParams, chain.request()));
//        if (chain.request().url().toString().contains("index/logout")) {
//            SPUtils.getInstance("loginuser").clear();
//        }
//        if (AppUtils.getAppVersionName().split("\\.").length != 3) {
//            throw new UnsupportedOperationException("versionName 的格式必须遵循与服务端约定的 \"x.x.x\" (三位版本号)\n形如：5.3.0、6.0.0、7.0.0、8.1.0");
//        }
        Request.Builder mRequestBuilder = chain.request().newBuilder();
        for (String key : headerParams.keySet()) {
            mRequestBuilder.addHeader(key, Objects.requireNonNull(headerParams.get(key)));
        }
        return chain.proceed(mRequestBuilder.build());
    }


    static String getMessageDigest(byte[] buffer) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str);
        } catch (Exception var9) {
            return null;
        }
    }


    public static String calcSign(Map<String, String> headerParams, Request request) {
        Map<String, String> params = new HashMap<>();
        if (request.method().equals("GET")) {
            HttpUrl url = request.url();
            Iterator var11 = url.queryParameterNames().iterator();

            while (var11.hasNext()) {
                String str = (String) var11.next();
                params.put(str, url.queryParameter(str));
            }
        } else if (request.method().equals("POST")) {

            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); ++i) {
                    params.put(body.name(i), body.value(i));
                }
            }

        } else {
            return null;
        }
        params.putAll(headerParams);

//        $contract['addressid'] = '1036';
//        $contract['approvers'] = '14602';
//        $contract['attachment'] = '';
//        $contract['breachpercent'] = '2';
//        $contract['buyer'] = '江苏徐州市云龙区公司';
//        $contract['code'] = '33666';
//        $contract['deliverytime']='1609343999';
//        $contract['generalconditionids'] = '12,13,14';
//        $contract['isapprove'] = '1';
//        $contract['orderid'] = '314';
//        $contract['remark'] = '';
//        $contract['resid'] = '1377';
//        $contract['restype'] = '106';
//        $contract['seller'] = '444444';
//        $contract['selleruserid'] = '15949';
//        $contract['title'] = '好像有点';
//        $contract['unloader'] = '甲方';
//
//        $contract['timestamp'] = '1609141869';
//        $contract['nonce'] = 'b87f85e051a74b748b8e64ad60fd04bf';
//        $contract['token'] = 'f32ddee9f7e583102d23eca0eb536715863830';
//        $contract['userid'] = '14602';
//        $contract['appversion'] = 'ios.6.8.0';

//        params.clear();
//        params.put("addressid", "1036");
//        params.put("approvers", "14602");
//     //   params.put("attachment", "");
//        params.put("breachpercent", "2");
//        params.put("buyer", "江苏徐州市云龙区公司");
//        params.put("code", "33666");
//        params.put("deliverytime", "1609343999");
//        params.put("generalconditionids", "12,13,14");
//        params.put("isapprove", "1");
//        params.put("orderid", "314");
//        params.put("remark", "");
//        params.put("resid", "1377");
//        params.put("restype", "106");
//        params.put("seller", "444444");
//        params.put("selleruserid", "15949");
//        params.put("title", "好像有点");
//        params.put("unloader", "甲方");
//
//        params.put("timestamp", "1609141869");
//        params.put("nonce", "b87f85e051a74b748b8e64ad60fd04bf");
//        params.put("token", "f32ddee9f7e583102d23eca0eb536715863830");
//        params.put("userid", "14602");
//        params.put("appversion", "ios.6.8.0");


        return sortMapMD5(params, ServerFlavorConfig.API_SIGN_KEY);
    }

    public static String sortMapMD5(Map<String, String> map, String key) {
        List<Map.Entry<String, String>> infos = new ArrayList<>(map.entrySet());
        Collections.sort(infos, (o1, o2) -> (o1.getKey().compareTo(o2.getKey())));

        char enter = 10;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < infos.size(); i++) {
            Map.Entry<String, String> ent = infos.get(i);
            String value = ent.getValue();

            sb.append(ent.getKey() + "=" + value + "&");
        }
        sb.append("key=" + key);

        String md5 = StringUtils.lowerCase(getMessageDigest(sb.toString().getBytes()).toString());
        //  String md52 = org.apache.commons.lang3.StringUtils.lowerCase(getMessageDigest(sb.toString().getBytes()).toString());
        return md5;

    }
}
